﻿#include <unistd.h>
#include <stdio.h>
#include <glog/logging.h>
#include <QString>

#include "include/util/utils.h"
#include "manager/config_manager.h"

Utils::Utils()
{
}

QString Utils::get_client_id() {
    char hostname[MAX_HOSTNAME_SIZE];
    char client_id[MAX_CLIENT_ID_SIZE];

    memset(hostname, 0, sizeof(hostname));
    gethostname(hostname, MAX_HOSTNAME_SIZE);

    sprintf(client_id, "%s-%d", hostname, getpid());
    QString strCliendId(client_id);

    return strCliendId;
}

char *Utils::str_to_char_array(QString str) {
    int len = str.toLatin1().length();
    char *data = new char[len + 1];
    memset(data, 0, len + 1);
    memcpy(data, str.toLatin1().data(), len);
    return data;
}

std::vector<uchar> Utils::mat_to_image(QSharedPointer<Mat> sp_frame, QString type) {
     vector<uchar> buff;
     vector<int> param = vector<int>(2);
    if (type == "jpg") {
        LOG(INFO) << "Utils | mat_to_image | jpg";
        param[0] = CV_IMWRITE_JPEG_QUALITY;
        param[1] = 95;
        imencode(".jpg", *sp_frame, buff, param);
    }
    if (type == "png") {
        LOG(INFO) << "Utils | mat_to_image | png";
        param[0] = CV_IMWRITE_PNG_COMPRESSION;
        param[1] = 3;
        imencode(".png", *sp_frame, buff, param);
    }
    return buff;
}

std::vector<cv::Point2f> Utils::parse_points(QString str_points) {
    LOG(INFO) << "Utils | parse_points | str_points" << str_points.toStdString();

    QString left_top = str_points.section(':', 0, 0);
    QString left_bottom = str_points.section(':', 1, 1);
    QString right_bottom = str_points.section(':', 2, 2);
    QString right_top = str_points.section(':', 3, 3);

    std::vector<cv::Point2f> v_points;
    v_points.push_back(parse_point(left_top));
    v_points.push_back(parse_point(left_bottom));
    v_points.push_back(parse_point(right_bottom));
    v_points.push_back(parse_point(right_top));

    return v_points;
}

cv::Point2f Utils::parse_point(QString str_point) {
    LOG(INFO) << "Utils | parse_point | str_point" << str_point.toStdString();
    float x = str_point.section('x', 0, 0).toFloat();
    float y = str_point.section('x', 1, 1).toFloat();
    cv::Point2f pnt;
    pnt.x = x;
    pnt.y = y;
    return pnt;
}

// 返回当前是否是行人检测系统
bool Utils::is_detect_pedestrian()
{
    AppConfig *ptr_app_config = ConfigManager::getInstance()->get_app_config();
    return (ptr_app_config->algorithm_type == ALGORITHM_TYPE_PEDESTRIAN);
}

QString Utils::get_points_str(std::vector<cv::Point2f> points) {
    if (points.size() != CALIBRATE_POINT_COUNT) {
        return "500x500:550x880:830x880:830x500";
    } else {
        return QString("%1x%2:%3x%4:%5x%6:%7x%8")
                .arg(points[0].x).arg(points[0].y)
                .arg(points[1].x).arg(points[1].y)
                .arg(points[2].x).arg(points[2].y)
                .arg(points[3].x).arg(points[3].y);
    }
}
